<?php
/**
* @version		1.0 MynxxRunonce
* @package		MynxxRunonce
* @copyright	Copyright (C) 2008 RocketTheme, LLC. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * MynxxRunonce analytics plugin
 *
 * @author		Andy Miller
 * @package		MynxxRunonce
 * @subpackage	System
 */
class  plgSystemMynxx_Runonce extends JPlugin
{

	function plgSystemMynxx_Runonce(& $subject, $config)
	{
		parent::__construct($subject, $config);
	}


	function onAfterInitialise()
	{
		global $mainframe;

		$vmconfig = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_virtuemart'.DS.'virtuemart.cfg.php';
		$placeholder = '%%BASEURL%%';
		$success = false;
		
		jimport( 'joomla.filesystem.folder' );
        jimport( 'joomla.filesystem.file' );
        jimport( 'joomla.filesystem.path' );

        //if virtuemart config exists
        if ( JFile::exists($vmconfig) ) {
            $config_file = JFile::read ($vmconfig);
            //if config has not already been set with proper JURI::root()
            if (strpos($config_file,$placeholder)) {
                //update with JURI::root
                $config_file = str_replace($placeholder,JURI::root(),$config_file);
                //try to update the file
                if (!Jfile::write($vmconfig,$config_file)) {
                    $mainframe->enqueueMessage("cannot write to file: ".$vmconfig,"error"); 
                    $success = false;  
                } else {
                    $success = true;
                }
            } else {
                $success = true;
            } 
        }
        // config exists, touch runonce flag
        if ($success) {
            $db	=& JFactory::getDBO();
            $sql = "UPDATE #__plugins SET published=0 WHERE element='mynxx_runonce'";
            $db->setQuery( $sql );
            $db->query();
        }
       
	}
}